<!--
 * 车辆违规管理
 *
-->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
                ><i
                    class="iconfont icon-warning-menu"
                    style="margin-right: 5px; font-size: 22px; color: #e6a23c;"
                ></i>车辆违规管理</el-breadcrumb-item
            >
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input
                        placeholder="请输入车牌号"
                        v-model="queryInfo.plateNumber"
                        clearable
                    ></el-input>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryInfo.violationType" placeholder="违规类型" clearable>
                        <el-option 
                            v-for="item in violationTypes" 
                            :key="item.value" 
                            :label="item.label" 
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryInfo.status" placeholder="处理状态" clearable>
                        <el-option label="未处理" value="0"></el-option>
                        <el-option label="已处理" value="1"></el-option>
                        <el-option label="已申诉" value="2"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="success"
                        icon="iconfont icon-search-menu"
                        style="font-size: 18px"
                        @click="searchViolations"
                    >
                        搜索</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="info"
                        icon="el-icon-refresh"
                        style="font-size: 18px"
                        @click="resetSearch"
                    >
                        重置</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="primary"
                        icon="iconfont icon-add-button"
                        style="font-size: 18px"
                        @click="addViolation"
                    >
                        新增违规</el-button
                    >
                </el-col>
            </el-row>

            <!-- 违规记录表格 -->
            <el-table v-loading="loading" :data="violations" border stripe>
                <el-table-column width="50" label="序号" align="center" type="index"></el-table-column>
                <el-table-column label="车牌号" prop="plateNumber" align="center"></el-table-column>
                <el-table-column label="违规类型" prop="violationType" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getViolationTypeTag(scope.row.violationType)">
                            <i class="el-icon-warning-outline" style="margin-right: 3px;"></i>
                            {{ getViolationTypeText(scope.row.violationType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="违规时间" prop="violationTime" align="center">
                    <template slot-scope="scope">
                        {{ formatDateTime(scope.row.violationTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="违规描述" prop="description" align="center"></el-table-column>
                <el-table-column label="罚款金额" prop="fine" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.fine }}元
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status" align="center">
                    <template slot-scope="scope">
                        <el-tag type="danger" v-if="scope.row.status === '0'">
                            <i class="el-icon-circle-close" style="margin-right: 3px;"></i>未处理
                        </el-tag>
                        <el-tag type="success" v-else-if="scope.row.status === '1'">
                            <i class="el-icon-check" style="margin-right: 3px;"></i>已处理
                        </el-tag>
                        <el-tag type="warning" v-else-if="scope.row.status === '2'">
                            <i class="el-icon-info" style="margin-right: 3px;"></i>已申诉
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="220">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.status === '0'"
                            @click="handleViolation(scope.row)"
                            type="primary"
                            size="mini"
                        >处理</el-button>
                        <el-button
                            @click="viewViolationDetails(scope.row)"
                            type="info"
                            size="mini"
                        >查看</el-button>
                        <el-button
                            v-if="scope.row.status === '0'"
                            @click="deleteViolation(scope.row.id)"
                            type="danger"
                            size="mini"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total"
            ></el-pagination>
        </el-card>

        <!-- 新增违规对话框 -->
        <el-dialog
            title="新增违规记录"
            :visible.sync="addViolationVisible"
            width="500px"
            center
            @close="resetViolationForm"
        >
            <el-form :model="violationForm" :rules="violationRules" ref="violationForm" label-width="100px">
                <el-form-item label="车牌号" prop="plateNumber">
                    <el-input v-model="violationForm.plateNumber" placeholder="请输入车牌号"></el-input>
                </el-form-item>
                <el-form-item label="违规类型" prop="violationType">
                    <el-select v-model="violationForm.violationType" placeholder="请选择违规类型" style="width: 100%">
                        <el-option 
                            v-for="item in violationTypes" 
                            :key="item.value" 
                            :label="item.label" 
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="违规时间" prop="violationTime">
                    <el-date-picker
                        v-model="violationForm.violationTime"
                        type="datetime"
                        placeholder="选择违规时间"
                        style="width: 100%"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="违规描述" prop="description">
                    <el-input
                        type="textarea"
                        v-model="violationForm.description"
                        placeholder="请输入违规详细描述"
                        :rows="3"
                    ></el-input>
                </el-form-item>
                <el-form-item label="罚款金额" prop="fine">
                    <el-input-number v-model="violationForm.fine" :min="0" :step="10" step-strictly></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addViolationVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitViolationForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 违规处理对话框 -->
        <el-dialog
            title="违规处理"
            :visible.sync="handleViolationVisible"
            width="500px"
            center
        >
            <div v-if="currentViolation" class="violation-details">
                <div class="detail-section">
                    <h4>违规信息</h4>
                    <div class="detail-item">
                        <span class="detail-label">车牌号：</span>
                        <span class="detail-value">{{ currentViolation.plateNumber }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">违规类型：</span>
                        <span class="detail-value">{{ getViolationTypeText(currentViolation.violationType) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">违规时间：</span>
                        <span class="detail-value">{{ formatDateTime(currentViolation.violationTime) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">罚款金额：</span>
                        <span class="detail-value">{{ currentViolation.fine }}元</span>
                    </div>
                </div>
                <div class="detail-section">
                    <h4>处理意见</h4>
                    <el-form :model="handleForm" :rules="handleRules" ref="handleForm" label-width="100px">
                        <el-form-item label="处理方式" prop="handleType">
                            <el-radio-group v-model="handleForm.handleType">
                                <el-radio :label="1">罚款处理</el-radio>
                                <el-radio :label="2">警告处理</el-radio>
                                <el-radio :label="3">申诉通过</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="处理备注" prop="remark">
                            <el-input
                                type="textarea"
                                v-model="handleForm.remark"
                                placeholder="请输入处理备注"
                                :rows="3"
                            ></el-input>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleViolationVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitHandleForm">确认处理</el-button>
            </span>
        </el-dialog>

        <!-- 违规详情对话框 -->
        <el-dialog
            title="违规详情"
            :visible.sync="detailsVisible"
            width="600px"
            center
        >
            <div v-if="currentViolation" class="violation-details">
                <div class="detail-section">
                    <h4>基本信息</h4>
                    <div class="detail-item">
                        <span class="detail-label">车牌号：</span>
                        <span class="detail-value">{{ currentViolation.plateNumber }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">违规类型：</span>
                        <span class="detail-value">{{ getViolationTypeText(currentViolation.violationType) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">违规时间：</span>
                        <span class="detail-value">{{ formatDateTime(currentViolation.violationTime) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">违规描述：</span>
                        <span class="detail-value">{{ currentViolation.description }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">罚款金额：</span>
                        <span class="detail-value">{{ currentViolation.fine }}元</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">状态：</span>
                        <span class="detail-value">
                            <el-tag type="danger" v-if="currentViolation.status === '0'">未处理</el-tag>
                            <el-tag type="success" v-else-if="currentViolation.status === '1'">已处理</el-tag>
                            <el-tag type="warning" v-else-if="currentViolation.status === '2'">已申诉</el-tag>
                        </span>
                    </div>
                </div>
                <div class="detail-section" v-if="currentViolation.status === '1' || currentViolation.status === '2'">
                    <h4>处理信息</h4>
                    <div class="detail-item">
                        <span class="detail-label">处理时间：</span>
                        <span class="detail-value">{{ formatDateTime(currentViolation.handleTime) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">处理方式：</span>
                        <span class="detail-value">
                            <el-tag type="primary" v-if="currentViolation.handleType === 1">罚款处理</el-tag>
                            <el-tag type="info" v-else-if="currentViolation.handleType === 2">警告处理</el-tag>
                            <el-tag type="warning" v-else-if="currentViolation.handleType === 3">申诉通过</el-tag>
                        </span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">处理备注：</span>
                        <span class="detail-value">{{ currentViolation.remark || '无' }}</span>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from "axios";

export default {
    data() {
        return {
            loading: false,
            total: 0,
            violations: [],
            // 查询参数
            queryInfo: {
                plateNumber: "",
                violationType: "",
                status: "",
                pagenum: 1,
                pageSize: 10
            },
            // 违规类型选项
            violationTypes: [
                { value: "1", label: "超时停车" },
                { value: "2", label: "占用他人车位" },
                { value: "3", label: "未缴费" },
                { value: "4", label: "乱停乱放" },
                { value: "5", label: "损坏设施" },
                { value: "6", label: "其他违规" }
            ],
            // 新增违规对话框
            addViolationVisible: false,
            violationForm: {
                plateNumber: "",
                violationType: "",
                violationTime: new Date(),
                description: "",
                fine: 50,
                status: "0"
            },
            violationRules: {
                plateNumber: [
                    { required: true, message: "请输入车牌号", trigger: "blur" },
                    { min: 7, max: 8, message: "车牌号长度为7-8个字符", trigger: "blur" }
                ],
                violationType: [
                    { required: true, message: "请选择违规类型", trigger: "change" }
                ],
                violationTime: [
                    { required: true, message: "请选择违规时间", trigger: "change" }
                ],
                description: [
                    { required: true, message: "请输入违规描述", trigger: "blur" }
                ],
                fine: [
                    { required: true, message: "请输入罚款金额", trigger: "blur" }
                ]
            },
            // 违规处理对话框
            handleViolationVisible: false,
            currentViolation: null,
            handleForm: {
                handleType: 1,
                remark: ""
            },
            handleRules: {
                handleType: [
                    { required: true, message: "请选择处理方式", trigger: "change" }
                ],
                remark: [
                    { required: true, message: "请输入处理备注", trigger: "blur" }
                ]
            },
            // 违规详情对话框
            detailsVisible: false
        };
    },
    methods: {
        // 获取违规列表
        getViolationList() {
            this.loading = true;
            
            // 构建查询参数
            let params = {
                pagenum: this.queryInfo.pagenum,
                pageSize: this.queryInfo.pageSize
            };
            
            if (this.queryInfo.plateNumber) {
                params.plateNumber = this.queryInfo.plateNumber;
            }
            
            if (this.queryInfo.violationType) {
                params.violationType = this.queryInfo.violationType;
            }
            
            if (this.queryInfo.status) {
                params.status = this.queryInfo.status;
            }
            
            // API调用
            axios.post("http://localhost:9271/violation/list", params)
                .then(res => {
                    this.loading = false;
                    if (res.data.flag) {
                        this.violations = res.data.data.records;
                        this.total = res.data.data.total;
                    } else {
                        this.$message.error(res.data.message || "获取违规记录失败");
                    }
                })
                .catch((error) => {
                    this.loading = false;
                    console.error("获取违规记录失败", error);
                    this.$message.error("获取违规记录失败，请检查网络连接或后端服务是否启动");
                });
        },
        
        // 分页相关方法
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            // 当每页数量变化时，重置为第一页
            this.queryInfo.pagenum = 1;
            this.getViolationList();
        },
        
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getViolationList();
        },
        
        // 重置搜索条件
        resetSearch() {
            this.queryInfo.plateNumber = "";
            this.queryInfo.violationType = "";
            this.queryInfo.status = "";
            this.queryInfo.pagenum = 1;
            this.getViolationList();
        },
        
        // 搜索按钮点击事件
        searchViolations() {
            // 搜索时重置为第一页
            this.queryInfo.pagenum = 1;
            this.getViolationList();
        },
        
        // 获取违规类型文本
        getViolationTypeText(type) {
            const found = this.violationTypes.find(item => item.value === type);
            return found ? found.label : "未知类型";
        },
        
        // 获取违规类型标签类型
        getViolationTypeTag(type) {
            switch (type) {
                case "1":
                    return "warning";
                case "2":
                    return "danger";
                case "3":
                    return "info";
                case "4":
                    return "danger";
                case "5":
                    return "danger";
                default:
                    return "info";
            }
        },
        
        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) return '';
            
            // 如果已经是格式化的字符串，直接返回
            if (typeof dateTime === 'string' && dateTime.includes('-')) {
                return dateTime;
            }
            
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        
        // 新增违规
        addViolation() {
            this.violationForm = {
                plateNumber: "",
                violationType: "",
                violationTime: new Date(),
                description: "",
                fine: 50,
                status: "0"
            };
            this.addViolationVisible = true;
        },
        
        // 重置违规表单
        resetViolationForm() {
            if (this.$refs.violationForm) {
                this.$refs.violationForm.resetFields();
            }
        },
        
        // 提交违规表单
        submitViolationForm() {
            this.$refs.violationForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    
                    // 添加创建时间和更新时间
                    const violationData = {
                        ...this.violationForm,
                        createTime: new Date(),
                        updateTime: new Date()
                    };
                    
                    // 提交API
                    axios.post("http://localhost:9271/violation/add", violationData)
                        .then(res => {
                            this.loading = false;
                            if (res.data.flag) {
                                this.$message.success("违规记录添加成功");
                                this.addViolationVisible = false;
                                this.getViolationList();
                            } else {
                                this.$message.error(res.data.message || "添加失败");
                            }
                        })
                        .catch((error) => {
                            this.loading = false;
                            console.error("添加违规记录失败", error);
                            this.$message.error("添加失败，请检查网络连接或后端服务是否启动");
                        });
                }
            });
        },
        
        // 处理违规
        handleViolation(violation) {
            this.currentViolation = violation;
            this.handleForm = {
                handleType: 1,
                remark: ""
            };
            this.handleViolationVisible = true;
        },
        
        // 提交处理表单
        submitHandleForm() {
            this.$refs.handleForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    
                    // 处理数据
                    const params = {
                        id: this.currentViolation.id,
                        handleType: this.handleForm.handleType,
                        remark: this.handleForm.remark,
                        // 处理后的状态
                        status: this.handleForm.handleType === 3 ? "2" : "1",
                        handleTime: new Date()
                    };
                    
                    // 提交API
                    axios.post("http://localhost:9271/violation/handle", params)
                        .then(res => {
                            this.loading = false;
                            if (res.data.flag) {
                                this.$message.success("违规处理成功");
                                this.handleViolationVisible = false;
                                this.getViolationList();
                            } else {
                                this.$message.error(res.data.message || "处理失败");
                            }
                        })
                        .catch((error) => {
                            this.loading = false;
                            console.error("处理违规记录失败", error);
                            this.$message.error("处理失败，请检查网络连接或后端服务是否启动");
                        });
                }
            });
        },
        
        // 查看违规详情
        viewViolationDetails(violation) {
            this.currentViolation = violation;
            this.detailsVisible = true;
        },
        
        // 删除违规记录
        async deleteViolation(id) {
            try {
                // 确保 id 为数字类型
                const numericId = parseInt(id);
                console.log('删除违规记录，ID:', numericId);
                
                // 确认操作
                const confirmResult = await this.$confirm(
                    "此操作将永久删除该违规记录, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(err => {
                    console.log('用户取消删除操作');
                    return 'cancel';
                });
                
                if (confirmResult === 'cancel') {
                    return;
                }
                
                this.loading = true;
                
                // 直接使用 URL 参数方式传递 ID
                const res = await axios.get(`http://localhost:9271/violation/delete?id=${numericId}`);
                console.log('删除API返回结果:', res.data);
                
                this.loading = false;
                
                if (res.data && res.data.flag) {
                    this.$message.success("删除成功");
                    this.getViolationList();
                } else {
                    const errorMsg = res.data ? res.data.message : "未知错误";
                    console.error("删除失败原因:", errorMsg);
                    this.$message.error(`删除失败: ${errorMsg || "服务器返回错误"}`);
                }
            } catch (error) {
                this.loading = false;
                console.error("删除操作异常:", error);
                this.$message.error("删除失败，请检查网络连接或后端服务");
            }
        }
    },
    mounted() {
        this.getViolationList();
    }
};
</script>

<style scoped>
.el-card {
    margin-top: 15px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-input, .el-select {
    margin-bottom: 15px;
}

/* 违规详情样式 */
.violation-details {
    padding: 10px;
}

.detail-section {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.detail-section:last-child {
    border-bottom: none;
}

.detail-section h4 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
    color: #303133;
}

.detail-item {
    margin-bottom: 10px;
    display: flex;
}

.detail-label {
    width: 120px;
    font-weight: bold;
    color: #606266;
}

.detail-value {
    flex: 1;
}
</style> 